<template>
	<view class="uni-flex-column container">
		<z-paging ref="pagingRef" v-model="dataList" @query="queryList" class="content">
			<template #top>
				<view class="uni-flex uni-justify-between top_container">
					<text class="num">共{{ totalNum }}个项目</text>
					<text class="manager" @click="toggleManager">{{
            isManager ? "退出管理" : "管理"
          }}</text>
				</view>
			</template>
			<view class="shop_item" v-for="(group, index) in dataList" :key="index">
				<view class="uni-flex shop_item_top">
					<radio color="#2F80ED" :checked="group?.isCheck" @click.stop="toggleGroupCheck(group)"
						style="transform: scale(0.7)" />
					<!-- <checkbox
            color="#2F80ED"
            :checked="group?.isCheck"
            @click="toggleGroupCheck(group)"
          /> -->
					<text class="name">{{ group?.itemName }}</text>
				</view>
				<view v-for="(itemChild, index) in group.list" :key="index" class="uni-flex item">
					<radio color="#2F80ED" :checked="itemChild.isCheck" @click.stop="toggleItemCheck(itemChild)"
						style="transform: scale(0.7)" />
					<!-- <checkbox
            :checked="itemChild.isCheck"
            @click="toggleItemCheck(itemChild)"
          /> -->
					<image :src="itemChild?.baseSmallImgUrl" mode="aspectFill" class="img"></image>
					<view class="uni-flex-column info">
						<text class="title">{{ itemChild?.specsName }}</text>
						<text class="des">{{ itemChild?.priceParamName }}</text>
						<text class="num">x{{ itemChild?.quantity }}</text>
					</view>
					<view class="uni-flex-column" style="align-items: flex-end">
						<text class="price">¥ {{ itemChild?.preferentialPrice }}</text>
						<text class="old_price">¥ {{ itemChild?.priceAmount }}</text>
						<!-- <uni-number-box
              v-model="vModelValue"
              @blur="blur"
              @focus="focus"
              @change="changeValue"
            /> -->
					</view>
				</view>
			</view>
			<template #empty>
				<!-- <empty-view /> -->
				<view>暂无数据</view>
			</template>
			<template #bottom>
				<view class="uni-flex uni-justify-between footer">
					<view @click="toggleCheckAll">
						<radio color="#2F80ED" :checked="isAllSelected" style="transform: scale(0.7)" />
						<text class="all">全选</text>
					</view>
					<view class="uni-flex">
						<view class="uni-flex-column" v-show="!isManager">
							<view>
								<text class="total">合计：</text>
								<text class="price">¥{{ selectedTotal }}</text>
							</view>
							<text class="discount">本单优惠¥{{ discountAmount }}</text>
						</view>
						<text :class="['btn', isManager ? 'delete' : 'settlement']"
							@click="settlementClick">{{ isManager ? "删除" : "结算" }}</text>
					</view>
				</view>
			</template>
		</z-paging>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from "vue";
	import {
		queryCartList,
		deleteCart,
		updateQuantity
	} from "@/api/cart.js";
	import {
		platformCreate
	} from "@/api/consumerOrder.js";
	import {
		useCartStore
	} from '@/store/cart.js';
	const vModelValue = ref(3);
	const totalNum = ref(0);
	const pagingRef = ref(null);
	// 响应式数据
	const dataList = ref([]);
	// 是否点击了管理
	const isManager = ref(false);
	const isAllSelected = ref(false);
	const cartStore = useCartStore()
	// 关键：进入购物车页面时强制刷新数量
	onMounted(async () => {
		await queryList(1, 9999); // 加载购物车列表
		await cartStore.initCartCount(); // 同步更新数量
	});
	// 管理
	const toggleManager = () => {
		isManager.value = !isManager.value;
	};
	// 全选/取消全选
	const toggleCheckAll = () => {
		const shouldSelectAll = !isAllSelected.value;
		dataList.value.forEach((group) => {
			group.isCheck = shouldSelectAll;
			group.list.forEach((item) => {
				item.isCheck = shouldSelectAll;
			});
		});
		isAllSelected.value = shouldSelectAll;
	};

	// 切换大类的选中状态（全选/取消全选）
	const toggleGroupCheck = (group) => {
		console.log(group);
		group.isCheck = !group.isCheck;
		group.list.forEach((item) => {
			item.isCheck = group.isCheck; // 同步子项选中状态
		});
		// 更新全选状态
		isAllSelected.value = dataList.value.every((group) => group.isCheck);
	};

	// 切换小类的选中状态
	const toggleItemCheck = (item) => {
		item.isCheck = !item.isCheck;
		// 查找对应的 group
		const group = dataList.value.find((g) => g.list.includes(item));
		if (group) {
			// 检查该 group 下的所有 item 是否都被选中
			group.isCheck = group.list.every((item) => item.isCheck);
		}
		// 更新全选状态
		isAllSelected.value = dataList.value.every((group) => group.isCheck);
	};
	// 计算选中的商品总价（优惠价）
	const selectedTotal = computed(() => {
		return dataList.value
			.flatMap((group) => group.list)
			.filter((item) => item.isCheck)
			.reduce((sum, item) => sum + item.preferentialPrice * item.quantity, 0)
			.toFixed(2);
	});

	// 计算选中的商品原价总和
	const originalTotal = computed(() => {
		return dataList.value
			.flatMap((group) => group.list)
			.filter((item) => item.isCheck)
			.reduce((sum, item) => sum + item.priceAmount * item.quantity, 0)
			.toFixed(2);
	});

	// 计算优惠金额
	const discountAmount = computed(() => {
		return (originalTotal.value - selectedTotal.value).toFixed(2);
	});
	const settlementClick = () => {
		if (isManager.value) {
			// 删除逻辑（核心修改部分）
			const selectedItems = dataList.value
				.flatMap((group) => group.list)
				.filter((item) => item.isCheck);
			if (selectedItems.length === 0) { // 新增：判断是否有选中项
				uni.showToast({
					title: "请选择要删除的商品",
					icon: "none"
				});
				return;
			}
			const ids = selectedItems.map((item) => item.shoppingId);
			deleteCart(ids).then((res) => {
				if (res.code == 200) {
					uni.showToast({
						title: "删除成功",
						icon: "success",
					});
					// 关键修复1：删除成功后重新查询列表数据并刷新页面
					queryList(1, 9999).then(() => {
						// 关键修复2：手动清空现有列表，确保UI重新渲染
						dataList.value = [];
						// 刷新后重新分组并更新数据
						pagingRef.value?.reload(); // 强制z-paging重新加载
					});
					// 更新购物车数量
					queryCartList({
						pageNum: 1,
						pageSize: 9999
					}).then(cartRes => {
						cartStore.updateCartCount(cartRes.rows.length)
					});
				}
			}).catch(err => { // 新增：捕获删除接口异常
				console.error("删除失败:", err);
				uni.showToast({
					title: "删除失败，请重试",
					icon: "none"
				});
			});
		} else {
			// 1. 获取选中的商品
			const selectedItems = dataList.value
				.flatMap((group) => group.list) // 扁平化所有子商品
				.filter((item) => item.isCheck); // 筛选选中的商品

			if (selectedItems.length === 0) {
				uni.showToast({
					title: "请选择商品",
					icon: "none"
				});
				return;
			}

			// 2. 提取选中商品的 itemId（核心步骤）
			// 若多个商品可能属于同一 itemId，可去重；若需所有 itemId，直接收集数组
			const selectedItemIds = selectedItems.map(item => item.itemId);
			// 去重处理（可选，根据业务需求）
			const uniqueItemIds = [...new Set(selectedItemIds)];

			// 3. 结算接口参数（原逻辑不变）
			const priceIds = selectedItems.map((item) => item.localPriceId);

			platformCreate({
				priceIds
			}).then((res) => {
				if (res.code === 200) {
					uni.showToast({
						title: "下单成功",
						icon: "success"
					});

					// 4. 传递参数：拼接订单 id、itemId 到路由（关键修改）
					// 若 itemId 是多个，用逗号分隔为字符串传递
					const itemIdsStr = uniqueItemIds.join(',');
					uni.navigateTo({
						url: `/pages/order/consumerOrder/placeOrder?` +
							`id=${res.data.id}` + // 订单 id
							`&itemIds=${itemIdsStr}`, // 选中商品的 itemId 集合
					});

					// 刷新购物车列表
					queryList(1, 10);
				} else {
					uni.showToast({
						title: "下单失败",
						icon: "error"
					});
				}
			});
		}
	};
	// 列表数据请求
	const queryList = async (pageNum, pageSize) => {
		console.log("查询购物车列表，页码：", pageNum);
		try {
			const params = {
				pageNum: pageNum,
				pageSize: 9999,
			};
			const res = await queryCartList(params);
			console.log('res', res);
			if (res.code === 200) {
				const groupedData = groupByItemId(res.rows);
				// 关键：确保数据正确更新到dataList
				dataList.value = groupedData;

				cartStore.updateCartCount(res.rows.length); // 更新数量
				// 通知z-paging数据加载完成
				pagingRef.value?.complete(groupedData);
				// 更新总数显示
				totalNum.value = res.rows.length;
			} else {
				// 接口返回错误时处理
				pagingRef.value?.complete([]);
				dataList.value = [];
				totalNum.value = 0;
				uni.showToast({
					title: "获取数据失败",
					icon: "none"
				});
			}
		} catch (error) {
			console.error("请求失败:", error);
			pagingRef.value?.complete(false);
		}
	};
	const groupByItemId = (data) => {
		totalNum.value = data.length;
		return data.reduce((groups, item) => {
			const foundGroup = groups.find((g) => g.itemId === item.itemId);
			if (foundGroup) {
				foundGroup.list.push({
					...item,
					isCheck: false, // 小类（商品）添加 isCheck: false
				});
			} else {
				groups.push({
					itemId: item.itemId,
					itemName: item.itemName,
					isCheck: false, // 大类（分组）添加 isCheck: false
					list: [{
						...item,
						isCheck: false, // 小类（商品）添加 isCheck: false
					}, ],
				});
			}
			return groups;
		}, []);
	};

	const changeValue = (value) => {
		console.log("返回数值：", value);
	};
	const blur = (e) => {
		console.log("blur:", e);
	};
	const focus = (e) => {
		console.log("focus:", e);
	};
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;

		.top_container {
			padding: 32rpx 24rpx;
			background-color: #fff;

			.num {
				font-size: 30rpx;
				color: #999;
			}

			.manager {
				font-size: 30rpx;
				color: #303133;
			}
		}

		.content {
			flex: 1;
			overflow-y: auto; // 添加滚动以防内容溢出
			background-color: #f5f5f5;
			padding-bottom: 25rpx;

			.shop_item_top {
				margin-bottom: 25rpx;

				.name {
					font-weight: 500;
					font-size: 36rpx;
					color: #333333;
					margin-left: 8rpx;
				}
			}

			.shop_item {
				margin: 24rpx 24rpx 0;
				background-color: #fff;
				border-radius: 16rpx;
				padding: 32rpx 24rpx;

				.item {
					margin-bottom: 32rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.img {
						width: 137rpx;
						height: 137rpx;
						margin-left: 8rpx;
						border-radius: 10rpx;
					}

					.info {
						flex: 1;
						margin-left: 24rpx;

						.title {
							font-weight: 500;
							font-size: 28rpx;
							color: #333333;
						}

						.des {
							font-weight: 400;
							font-size: 28rpx;
							color: #666666;
							margin-top: 5rpx;
						}

						.num {
							font-size: 28rpx;
							color: #666666;
							margin-top: 12rpx;
						}
					}

					.price {
						font-weight: 500;
						font-size: 30rpx;
						color: #ff6a47;
					}

					.old_price {
						font-weight: 400;
						font-size: 24rpx;
						color: #999999;
						text-decoration: line-through;
						margin-top: 10rpx;
					}
				}
			}
		}

		.footer {
			background-color: #fff;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 14rpx 24rpx;

			.all {
				font-size: 28rpx;
				color: #666666;
			}

			.total {
				font-size: 24rpx;
				color: #333333;
			}

			.price {
				font-size: 30rpx;
				color: #ff6a47;
			}

			.discount {
				font-size: 24rpx;
				color: #ff6a47;
				margin-top: 10rpx;
			}

			.btn {
				width: 260rpx;
				height: 88rpx;
				border-radius: 49rpx;
				font-size: 36rpx;
				text-align: center;
				line-height: 88rpx;
				margin-left: 16rpx;
				color: white;
			}

			.settlement {
				background: #2f80ed;
			}

			.delete {
				background: #eb4747;
			}
		}
	}
</style>